package fivestar.model.dao.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import fivestar.model.dao.CityDao;
import fivestar.model.entity.City;
import fivestar.util.HibernateUtil;

public class CityDaoHibernate implements CityDao {

	Session session = null;
	Transaction tx = null;
	
	@Override
	public void create(City city) throws RuntimeException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void delete(City city) throws RuntimeException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void update(City city) throws RuntimeException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public City find(int id) throws RuntimeException {
		City city= null;
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("from City where cityId= :cityId");
			query.setInteger("cityId", id);
			city = (City) query.uniqueResult();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		return city;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> findAll(String country) throws RuntimeException {
		String temp = country + "%";
		List<String> lista = null;
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			//lista = session.getNamedQuery("findAllGuestAddress").list();
		 Query query = session.createQuery("select distinct ci.city from City  as ci inner join ci.country co where co.country like ?");
		 query.setString(0, temp);
		 
		 lista =  query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		return lista;
	}

	@Override
	public Short findID(String city) throws RuntimeException {

        Short id = null; 
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            tx = session.beginTransaction(); 
            Query query = session.createQuery("select c.cityId from City c where c.city=:city");
            query.setString("city", city);
            id = (Short) query.uniqueResult();
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return id;
    
	}
	
	

}
